package com.woniu.springboot.saleTickit;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author zhaolei
 * @date 2021/5/8 - 2:03
 */
@RestController
public class saleKillController {
    @Autowired
    private StringRedisTemplate redisTemplate;
    @GetMapping(value = "/sale")
    public String salePiao(){
        synchronized (this){
            int stock = Integer.parseInt(redisTemplate.opsForValue().get("stock"));
            if (stock>0){
                int realStock = stock - 1;
                redisTemplate.opsForValue().set("stock",String.valueOf(realStock));
                System.out.println("抢购成功，你抢了第" + stock + "张票，余票为" + realStock + "张");
                return "抢购成功，余票为" + realStock + "张票";
            }else {
                System.out.println("抢购活动已结束");
                return "抢购活动已结束，请下次再试";
            }
        }

    }
}
